import easyquotation
import time
import datetime as dt
import json





from datetime import datetime

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS


import csv



# You can generate an API token from the "API Tokens Tab" in the UI
token = "9Qt0Z7iD-o1eIrA46UfmXhbk7vw02OmU819iLMdVIiZXSNtoHFE38l3c40DMBZb9CK2xjh9ZJy0hYLPsTl5DRw=="
org = "as_influx"
buckets = "test_data3"




class InfluxClient:
    def __init__(self,token,org,bucket): 
        self._org=org 
        self._bucket = bucket
        self._client = InfluxDBClient(url="http://43.142.185.110:8086", token=token)

    def write_data(self,data,write_option=SYNCHRONOUS):
        write_api = self._client.write_api(write_option)
        write_api.write(self._bucket, self._org , data,write_precision='s')

    def query_data(self,query):
        query_api = self._client.query_api()
        result = query_api.query(org=self._org, query=query)
        results = []
        for table in result:
            for record in table.records:
                results.append((record.get_value(), record.get_field()))
        print(results)
        return results 
    
    def delete_data(self,measurement):
        delete_api = self._client.delete_api()
        start = "1970-01-01T00:00:00Z"
        stop = "2021-10-30T00:00:00Z"
        delete_api.delete(start, stop, f'_measurement="{measurement}"', bucket=self._bucket, org=self._org)


IC = InfluxClient(token,org,buckets)


class Market:
    def _init__(self):
        self.lastPx = 0
        self.ask1 = 0
        self.bid1 = 0
        self.ask_vol1 = 0
        self.bid_vol1 = 0
        self.trade_vol = 0
        self.open_price = 0
        self.time = dt.datetime.now()



def recv_market_to_influx():
    quotation = easyquotation.use('sina')
    init_trade_pre = 0
    ticker_name = '600438'
    fp = open('sh' + ticker_name + '.csv', 'a')
    while(True):
        time.sleep(1)
        market = str(quotation.real('sh' + ticker_name)) # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
        #print(market)
        market = market.replace("'", '"')
        market_json = json.loads(market)

        msg = Market()
        msg.lastPx     =  market_json[ticker_name]["now"]
        msg.ask1       =  market_json[ticker_name]["ask1"]
        msg.bid1       =  market_json[ticker_name]["bid1"]
        msg.ask_vol1   =  market_json[ticker_name]["ask1_volume"]
        msg.bid_vol1   =  market_json[ticker_name]["bid1_volume"]
        if init_trade_pre ==0:
            msg.trade_vol = 0
            init_trade_pre = market_json[ticker_name]["turnover"]
        else:
            msg.trade_vol  =  market_json[ticker_name]["turnover"] - init_trade_pre
            init_trade_pre = market_json[ticker_name]["turnover"]
        msg.open_price =  market_json[ticker_name]["open"]

        datetime_str = market_json[ticker_name]["date"]+" "+ market_json[ticker_name]["time"]
        datetime_object = dt.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        msg.time       =  datetime_object
        line = 'stock_sec_line,host=host1 ' + 'ticker=' + ticker_name + ',' + 'last_px=' + str(msg.lastPx) + ',' + 'ask1=' + str(msg.ask1) + ',' +'bid1=' + str(msg.bid1) + ',' + 'ask1_vol=' + str(msg.ask_vol1) + ',' + 'bid1_vol=' + str(msg.bid_vol1) + ',' + 'open_px=' + str(msg.open_price) + ',' +'amount='+ str(msg.trade_vol)
        IC.write_data(line)


def recv_market():
    quotation = easyquotation.use('sina')
    init_trade_pre = 0
    ticker_name = '600438'
    fp = open('sh' + ticker_name + '.csv', 'a')
    while(True):
        time.sleep(1)
        market = str(quotation.real('sh' + ticker_name)) # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
        #print(market)
        market = market.replace("'", '"')
        market_json = json.loads(market)

        msg = Market()
        msg.lastPx     =  market_json[ticker_name]["now"]
        msg.ask1       =  market_json[ticker_name]["ask1"]
        msg.bid1       =  market_json[ticker_name]["bid1"]
        msg.ask_vol1   =  market_json[ticker_name]["ask1_volume"]
        msg.bid_vol1   =  market_json[ticker_name]["bid1_volume"]
        if init_trade_pre ==0:
            msg.trade_vol = 0
            init_trade_pre = market_json[ticker_name]["turnover"]
        else:
            msg.trade_vol  =  market_json[ticker_name]["turnover"] - init_trade_pre
            init_trade_pre = market_json[ticker_name]["turnover"]
        msg.open_price =  market_json[ticker_name]["open"]
        msg.trade_vol = market_json[ticker_name]["turnover"]
        datetime_str = market_json[ticker_name]["date"]+" "+ market_json[ticker_name]["time"]
        datetime_object = dt.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        msg.time       =  datetime_object
        line = ticker_name + ',' +  str(msg.lastPx) + ',' + str(msg.ask1) + ',' + str(msg.bid1) + ',' + str(msg.ask_vol1) + ',' + str(msg.bid_vol1) + ',' + str(msg.open_price) + ',' + str(msg.trade_vol)+ ',' + str(msg.time) + '\n'
        fp.write(line)
        fp.flush()
recv_market_to_influx()
